//
//  OAuthViewController.swift
//  weibo
//
//  Created by hm on 2020/4/29.
//  Copyright © 2020 hm. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!
    
    lazy private var progressView: UIProgressView = {
        let progress = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: UIScreen.main.bounds.width, height: 2))
        progress.tintColor = UIColor.green
        progress.trackTintColor = UIColor.white
        return progress
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置顶部导航
        setupNavigationBar()
        
        //加载新浪微博登陆页
        loadLoginPage()
    }

}

extension OAuthViewController {
    
    private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",
                                                           style: .plain,
                            target: self,
                            action: #selector(self.closeItemClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充",
                                                            style: .plain,
                                                            target: self,
                                                            action: #selector(self.fillItemClick))
    }
    
    private func loadLoginPage(){
        webView.navigationDelegate = self
//        webView.addObserver(self, forKeyPath: "url", options: .new, context: nil)
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_url)"
        
        guard let url = URL(string: urlStr) else {
            return
        }
        
        webView.load(URLRequest(url: url))
    }
}

extension OAuthViewController{
    @objc private func closeItemClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func fillItemClick(){
        //定义js代码
        let jsCode = "document.getElementById('userId').value='18086682486';document.getElementById('passWd').value='';"
        //执行js代码
        webView.evaluateJavaScript(jsCode)
    }
}

extension OAuthViewController: WKNavigationDelegate{
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("开始加载")
        SVProgressHUD.show()
    }
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        SVProgressHUD.show()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
        
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //监听url变化
    //截取新浪微博回调的url中的code
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        decisionHandler(.allow)
        
        guard let url = navigationAction.request.url?.absoluteString else {
            return
        }
        print(url)
        
        guard url.contains("code=") else {
            return
        }
        
        var code = url.components(separatedBy: "code=").last!
        code = code.components(separatedBy: "&").first!
        print("+++++++得到code++++++++++++++++++++++++++++++++++++++++++++")
        print(code)
        
        //获取accessToken
        loadAccessToken(codeString: code)
    }
    
    /// 加载accessToken
    private func loadAccessToken(codeString : String) {
        NetUtil.instance.loadAccessToken(codeString: codeString,
            finish: { (result) -> () in
                print("======获得access token===========================")
                print(result)
                
                //解析json
                let nsdicArr: NSDictionary = result as! NSDictionary
                let dicArr = nsdicArr as! [String: AnyObject]
                let userAccount = UserAccount(dict: dicArr)
                print(userAccount)
                
                //拉取用户数据
                NetUtil.instance.getUserInfo(accessToken: userAccount.access_token,
                                             uid: userAccount.uid,
                     finish: { (result) in
                        let nsDicArr = result as! NSDictionary
                        let dicArr = nsDicArr as! [String: AnyObject]
                        print("====获得user info==============================================")
                        print(dicArr)
                        
                        userAccount.avatar_large = dicArr["avatar_large"] as! String
                        userAccount.screen_name = dicArr["screen_name"] as! String
                        
                        print(userAccount)
                        
                    },
                     fail: { (error) in
                            print(error)
                    }
                )
                
            },
            fail: { (error) -> () in
                print(error)
            })
    }
    
}

